package com.test;

import com.test.mqtt.QosEnum;
import com.test.mqtt.client.EmqClient;
import com.test.mqtt.properties.EmqxProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;

@SpringBootApplication
public class EmqxStudyApplication {
    public static void main(String[] args) {
        SpringApplication.run(EmqxStudyApplication.class,args);
    }

    @Autowired
    private EmqClient emqClient;
    @Autowired
    private EmqxProperties emqxProperties;

    @PostConstruct  //项目启动的时候执行
    public void init(){
        // 连接服务端
        emqClient.connect(emqxProperties.getUsername(),emqxProperties.getPassword());
        // 订阅主题
        emqClient.subscribe("testtopic/#", QosEnum.Qos2);
        // 开启一个新的线程，每五秒向testtopic/123发布消息
        new Thread(()->{
            while (true){
                emqClient.publish(
                        "testtopic/123",
                        "publish msg：" + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME),
                        QosEnum.Qos2,
                        false
                );
                try {
                    TimeUnit.SECONDS.sleep(5); //睡眠五秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
